//
//  XLSearchViewController.m
//  XiangLove
//
//  Created by 李传坤 on 2018/8/7.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLSearchViewController.h"
#import "XLMyFriendTableCell.h"
#import "XLPersonPageViewController.h"
#import "NSString+Emoji.h"
#import "BMHPromptView.h"
#import "NSString+Ext.h"

@interface XLSearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>{
}
@property (nonatomic,strong) UISearchBar    *searchBar;
@property (nonatomic,strong) UITableView    *tableView;
@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic, strong) BMHPromptView      *promptView;
@end

@implementation XLSearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self addTableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGB(232, 229, 236);
    [self.navigationItem setHidesBackButton:YES];
    
    [self setMyNavigation];
    // 初始化搜索相关控制器
    [self addAllSearchControllers];
}

#pragma mark 设置navigation
- (void)setMyNavigation {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClickQX)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:RGB_HEX(0xffbb01)}];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.delegate = self;
    searchBar.barStyle = UIBarStyleBlack;
    searchBar.placeholder = @"请输入昵称或ID搜索";
    [searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
    [searchBar sizeToFit];
    searchBar.backgroundImage = [UIImage imageWithColor:[UIColor clearColor] size:searchBar.bounds.size];
    [self setSearchBarTextfiled:searchBar];
    searchBar.tintColor = RGB_HEX(0xffbb01);
    searchBar.delegate = self;
    self.navigationItem.titleView = searchBar;
    _searchBar = searchBar;
    [_searchBar becomeFirstResponder];
    
}

- (void)setSearchBarTextfiled:(UISearchBar *)searchBar {
    for (UIView *view in searchBar.subviews){
        for (id subview in view.subviews){
            if ( [subview isKindOfClass:[UITextField class]] ){
                UITextField *textField = (UITextField *)subview;
                [textField setBackgroundColor:RGB(251, 251, 251)];
                [textField setTextColor:[UIColor blackColor]];
                return;
            }
        }
    }
}
#pragma mark - getter
- (BMHPromptView *)promptView {
    if (_promptView == nil) {
        _promptView = [[BMHPromptView alloc] initWithImage:[UIImage imageNamed:@"pic_nothing_n"]];
        [_promptView.reTryButton setTitle:@"没有搜到用户" forState:UIControlStateNormal];
        [self.view addSubview:_promptView];
        [_promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(200, 215));
            make.center.equalTo(self.view).centerOffset(CGPointMake(0,-150));
        }];
    }
    return _promptView;
}
#pragma mark 点击键盘上<搜索>
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    // 更新searchbar显示
    _searchBar.text = searchBar.text;
    searchBar.text = [searchBar.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (searchBar.text.length != 0) {
        NSDictionary *dic = @{@"search":_searchBar.text};
        [[[XLHTTPSessionManager sharedManager]XLV2GET:@"Api/v2/UserInfo/SearchUser" parameters:dic resultClass:nil] subscribeNext:^(id x) {
            NSLog(@"==%@",x);
            [MBProgressHUD hideHUDForView:self.view];
            self.tableView.hidden = NO;
            
            NSArray * listAry = x;
            if (![x isKindOfClass:[NSNull class]] && listAry.count > 0) {
                [_promptView removeFromSuperview];
                _promptView = nil;
                [self getJsonArray:listAry];
            }else{
                self.promptView.hidden = NO;
                self.tableView.hidden = YES;
            }
        } error:^(NSError *error) {
            NSLog(@"%@", error);
            self.promptView.hidden = NO;
            self.tableView.hidden = YES;
            [MBProgressHUD hideHUDForView:self.view];
        }];
    }
    
}


- (void)getJsonArray:(NSArray *)array {
    if ([array isKindOfClass:[NSNull class]] || array.count == 0 || array == nil) {
        
    } else {
        [self.modelArray removeAllObjects];
        [self.modelArray addObjectsFromArray:array];
    }
    [self.tableView reloadData];
}
- (NSMutableArray *)modelArray
{
    if (_modelArray == nil) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
-(void)addTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, XQScreenW, XQScreenH) style:UITableViewStylePlain];
    _tableView.rowHeight = 86;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    [_tableView registerClass:[XLMyFriendTableCell class] forCellReuseIdentifier:NSStringFromClass([XLMyFriendTableCell class])];
    [self.view addSubview:_tableView];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLMyFriendTableCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLMyFriendTableCell class]) forIndexPath:indexPath];
    NSDictionary  *model = [self.modelArray objectAtIndex:indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.headerImageView setImageWithURL:[NSURL URLWithString:model[@"HeadImg"]] placeholder:[UIImage imageWithColor:RGB(255, 255, 255)]];
    cell.nickNameLabel.text = model[@"NickName"];
    if (cell.nickNameLabel.text.length == 0) {
        cell.nickNameLabel.text = @"      ";
    }
    [cell.nickNameLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView.mas_left).offset(65);
        make.top.equalTo(cell.contentView.mas_top).offset(32);
        make.right.equalTo(cell.contentView.mas_right).offset(-50);
    }];
    CGFloat width = [cell.nickNameLabel.text sizeWidthsFont:18 andHeight:20];
    width += 70;//加上头像
    cell.ageLabel.frame = CGRectMake(width, 34, 36, 16);
    cell.sexImage.frame = CGRectMake(width + 4, 36, 12, 12);
    cell.ageLabel.text = [NSString stringWithFormat:@"     %@",model[@"Age"]];
    if ([model[@"Sex"] integerValue] == 1) {
        cell.ageLabel.backgroundColor = RGB_HEX(0xFFA6D8);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nv_n"];
    }else{
        cell.ageLabel.backgroundColor = RGB_HEX(0xB7D0FF);
        cell.sexImage.image = [UIImage imageNamed:@"common_icon_nan_n"];
    }
    cell.infor.hidden = YES;
    cell.onlineState.hidden = YES;
    cell.levelImage.hidden = YES;
    cell.isFriend.hidden = YES;
    return  cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *model = self.modelArray[indexPath.row];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:XiangLove_IsSH] boolValue]) {
        [[TIMFriendshipManager sharedInstance] GetUsersProfile:@[NSStringFormat(@"%@",model[@"Id"])] succ:^(NSArray *friends) {
            for (TIMUserProfile *pro in friends)
            {
                IMAUser *user = [[IMAUser alloc] initWithUserInfo:pro];
                dispatch_async(dispatch_get_main_queue(), ^{
                    IMAChatViewController *chat = [[IMAChatViewController alloc] initWith:user];
                    chat.isAnchor = model[@"IsAnchor"];
                    [self.navigationController pushViewController:chat animated:YES ];
                });
            }
        } fail:^(int code, NSString *msg) {
            NSLog(@"msg");
        }];
        return;
    }
    XLPersonPageViewController *vc = [[XLPersonPageViewController alloc] init];
    vc.userId = [NSString stringWithFormat:@"%@",model[@"Id"]];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark 搜索框文字变化时调用
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    // 调用搜索-显示搜索提示todo
    if (searchText.length == 0) {
    }
}

#pragma mark - 点击取消
- (void)cancelClickQX {
    _searchBar.text = @"";
    // 隐藏键盘
    [_searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 初始化搜索相关控制
- (void)addAllSearchControllers {
    
}


- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0); {
    
    //禁止输入emoji表情
    if ([NSString stringContainsEmoji:text]) {
        
        [MBProgressHUD showContent:@"暂不支持表情功能!"];
        return NO;
    }
    return YES;
}



- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [_searchBar resignFirstResponder];
}

@end
